package com.tjnu.losca.core;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.tjnu.losca.pojo.Teacher;

/**
 * @author Losca
 * @date 2021/9/17 13:28
 */
public class JWTUtil {
    private static final String KEY = "Losca";

    /**
     *
     * @param teacher
     * @return返回token
     */
    public static String create(Teacher teacher){
        String s = JWT.create().withClaim("teaNo", teacher.getId())
                .withClaim("teaName", teacher.getName())
                .sign(Algorithm.HMAC256(KEY));
        return s;
    }

    public static Teacher decoder(String token) throws Exception {
        try {
            DecodedJWT decoder = JWT.require(Algorithm.HMAC256(KEY)).build().verify(token);
            Integer id = decoder.getClaim("teaNo").asInt();
            String name = decoder.getClaim("teaName").asString();
            Teacher teacher = new Teacher();
            teacher.setId(id);
            teacher.setName(name);
            return teacher;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("请求不合法");
        }

    }
}
